package com.csdj.t301.service;

import com.csdj.t301.constant.CommonConstant;
import com.csdj.t301.entity.User;
import com.csdj.t301.mapper.UserMapper;
import com.csdj.t301.util.EncryptUtil;
import com.csdj.t301.util.RandomUtil;
import com.csdj.t301.vo.WebResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

//import javax.annotation.Resource;

/**
 * author:cloud
 * date:2021/3/11 0011
 **/
@Service//交由spring来管理对象
public class UserService {

    @Resource
    private ICache cache;

    @Resource//通过spring把对象注入
    private UserMapper userMapper;


    public int getUserCount(){
        return userMapper.findUserCount();
    }

    @Transactional(rollbackFor = RuntimeException.class)
    public boolean update(User user){
        return userMapper.update(user) > 0;
    }

    public User getUser(int id){
        return userMapper.findById(id);
    }

    public WebResult login(String username, String password){
        //密码加密
        String depass = EncryptUtil.getMd5(password);
        User user = userMapper.login(username, depass);
        if(user == null){
            //登录失败
            return new WebResult(401);
        }else{
            //登录 成功
            //生成token 保存
            String token = RandomUtil.getToken();
            if(cache.set(CommonConstant.CACHE_TOKEN_PREFIX+user.getId(),token,CommonConstant.USER_LOGIN_EXPIRE)){
                final WebResult result = new WebResult(200);
                result.putData("token",token).putData("userId",user.getId());
                return result;
            }else{
                return new WebResult(0);
            }
        }


    }
}
